<template>
  <section class="content" id="content">
    <!-- 检索条件 -->
    <lq-form :form="searchForm" ref="searchFormRef">
      <template #footer>
        <div>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="success" @click="handleSave"> 新增</el-button>
          <el-button type="danger" @click="handleBatchRemove">批量删除</el-button>
          <el-button type="warning" size="small" @click="handleExport">导出</el-button>
        </div>
      </template>

    </lq-form>

    <br>
    <!-- 数据列表 -->
    <div id="table">
      <lq-table ref="tableRef"
                :columns="columns"
                :records="tableData.records"
                size="default"
                :border="true"
                :header-cell-style="{background:'#e1eaf6', color:'#333333'}"
                :stripe="true"
                :pagination="paginationProps"
                @on-selections="handleSelectionChange"
                @on-pagination="handleCurrentChange"
      >
        <template #name="scope">
          <el-link type="primary" @click="handleView(scope.row.id)">{{ scope.row.name }}</el-link>
        </template>

        <template #operate="scope">
          <el-button @click="handleEdit(scope.row.id)" type="primary">编辑</el-button>
          <el-button @click="handleSingleRemove(scope.row.id)" type="danger">删除</el-button>
        </template>

      </lq-table>
    </div>


    <el-dialog v-model="dialog.visible"
               v-bind="{...dialog.innerAttrs}"
               v-on="dialog.events">
      <EntEmployeeForm ref="addSafeDeviceOverhaulFormRef"  @flush="handleFlush"  />

    </el-dialog>


  </section>
</template>
<script setup lang="ts">
/**
 * --------------相关组件引入--------------------------
 */
import {ref, reactive, onMounted, getCurrentInstance, nextTick} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

import EntEmployeeForm from "@/pages/ent/safeDevice/SafeDeviceOverhaulForm.vue";
import LqForm from "@/pages/components/LqForm.vue";
import LqTable from "@/pages/components/LqTable.vue";


/**
 * --------------全局共享上下文引入--------------------------
 */
const global = getCurrentInstance().appContext.config.globalProperties;


/**
 * ---------------状态变量定义-------------------------
 */
//获取表格组件实例
const tableRef = ref();

//获取新增或编辑窗口组件实例
const addSafeDeviceOverhaulFormRef = ref();


const tableData = ref({
  records: [],
  pageSize: 10,
  tableSize: 'default',
  border: true,
});

//分页信息
const paginationProps = reactive({
  pageSize: tableData.value.pageSize,
  pageSizes: [5, 10, 20, 50, 100],
  total: 0,
  pageNum: 1,
  small: false,
  paginationAlign: 'right',
});


const searchForm = ref({
  innerAttrs: {
    labelPosition: 'right',
    labelWidth:  70,
  },
  model: {
    name: "",
    position: "",
    type: "",
    dept: "",
    mobilePhone: ""
  },
  formItems: [
    {type: 'input', label: '人员姓名: ', prop: 'name', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '岗位: ', prop: 'position', span: 4, maxlength: 30, placeholder: ''},
    {type: 'select', label: '人员类型: ', prop: 'type', span: 4, options: [{label: '主要负责人', value: '主要负责人'},{label: '安全负责人', value: '安全负责人'},{label: '安全生产管理人员', value: '安全生产管理人员'},{label: '特殊作业人员', value: '特殊作业人员'},{label: '特种设备作业人员', value: '特种设备作业人员'},{label: '其他', value: '其他'}], },
    {type: 'input', label: '所属部门: ', prop: 'dept', span: 4, maxlength: 30, placeholder: ''},
    {type: 'input', label: '联系电话: ', prop: 'mobilePhone', span: 4, maxlength: 30, placeholder: ''}
  ],
  buttonsAttrs: {
    align: 'left'
  }
});


const columns = [
  {label: '', type: "selection", width: 40},
  {label: '序号', type: "index", width: 50},
  {label: "编号", prop: 'id', minWidth: 100},
   {label: "大修名称", prop: 'name', minWidth: 100},
   {label: "装置类型", prop: 'deviceType', minWidth: 100},
   {label: "检修内容", prop: 'content', minWidth: 100},
   {label: "检修原因", prop: 'cause', minWidth: 100},
   {label: "(设施负责人)", prop: 'deviceHeadName', minWidth: 100},
   {label: "(设施负责人电话)", prop: 'deviceHeadPhone', minWidth: 100},
   {label: "开始时间", prop: 'startTime', minWidth: 100},
   {label: "计划结束时间", prop: 'expectEndTime', minWidth: 100},
   {label: "实际结束时间", prop: 'actualEndTime', minWidth: 100},
   {label: "大修责任人", prop: 'headName', minWidth: 100},
   {label: "大修责任人电话", prop: 'headPhone', minWidth: 100},
   {label: "备注", prop: 'remark', minWidth: 100},
   {label: "审核状态", prop: 'auditStatus', minWidth: 100},
   {label: "审核时间", prop: 'auditDate', minWidth: 100},
   {label: "所属单位", prop: 'orgId', minWidth: 100},
   {label: "排序号", prop: 'sort', minWidth: 100},
   {label: "更新人", prop: 'updateUser', minWidth: 100},
   {label: "更新时间", prop: 'updateTime', minWidth: 100},
   {label: "创建人", prop: 'createUser', minWidth: 100},
   {label: "创建时间", prop: 'createTime', minWidth: 100},
   {label: '操作', prop: 'id', slotName: 'operate', slotted: true, align: 'center', fixed: 'right', minWidth: 150},
]


const dialog = ref({
  visible: false,
  innerAttrs: {
    id: 'SafeDeviceOverhaulFormDialog',
    class: 'SafeDeviceOverhaulFormDialog',
    title: '企业装置大修',
    width: "60%",
    top: '6vh'
  },
  events: {
    open: () => {
      console.log('dialog open.....');

    },
    close: () => {
      console.log('dialog close.....');

    },
  }
})
/**
 * --------------页面加载生命周期函数--------------------------
 */
onMounted(() => {
  queryData();
})

/**
 * --------------搜索查询功能--------------------------
 */
const handleQuery = () => {
  //每次查询都要从第一页开始
  resetPagination();
  queryData();
}

/**
 * --------------AJAX获取数据--------------------------
 */
const queryData = () => {
  let data = Object.assign({}, searchForm.value.model, {pageNum: paginationProps.pageNum, pageSize: paginationProps.pageSize});
  let obj = global.$delUndefined(data);
  global.$api.getEntEmployeesPage(obj).then(({data}) => {
    if (data.status === 'OK') {
      tableData.value.records = data.data.list;
      paginationProps.total = data.data.total;
    }
  });
};

/**
 * --------------刷新-----------------
 */
const handleFlush = () => {
  dialog.value.visible = false;
  queryData();
}


/**
 * --------------分页操作-------------------
 */
const handleCurrentChange = () => {
  // 调用查询方法
  queryData();
};


const resetPagination = () => {
  paginationProps.pageNum = 1;
  paginationProps.pageSize = tableData.value.pageSize;
  paginationProps.total = 0;
};
/**
 * --------------编辑------------------
 */

const handleEdit = (id: string) => {
  dialog.value.visible = true;
  nextTick(()=>{
      addSafeDeviceOverhaulFormRef.value.handleViewOrEdit(id, false)
  })
}

/**
 * --------------只读设置-------------------
 */
const handleView = (id: string) => {
  dialog.value.visible = true;
  nextTick(()=>{
    addSafeDeviceOverhaulFormRef.value.handleViewOrEdit(id, true)
  })
}


/**
 * --------------新增--------------------------
 */

const handleSave = () => {
  //先清空表单，防止编辑污染
  dialog.value.visible = true;
  nextTick(()=>{
    addSafeDeviceOverhaulFormRef.value.handleReset()
  })

}


/**
 * --------------删除操作--------------------------
 */
const handleSingleRemove = (id: string) => {
  ElMessageBox.confirm(`确认要删除吗!`, "确认信息", {
    type: "warning",
    distinguishCancelAndClose: true,
    confirmButtonText: "删除",
    cancelButtonText: "取消",
  })
      .then(() => {
        global.$api
            .deleteSafeDeviceOverhaulById({
              id: id,
            }).then(({data}) => {
          queryData();
          ElMessage({
            type: "success",
            message: "您已经成功删除了信息",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "您已经取消了删除操作",
        });
      });

}


/**
 * --------------多选删除操作--------------------------
 */


//选择的记录集
const selections = ref([]);
const handleSelectionChange = (items) => {
  selections.value = items.value.map((item) => item.id);
  // console.log('选择的ID:',...toValue(selections));
}


// 删除功能
const handleBatchRemove = () => {
  if (selections.value.length === 0) {
    ElMessage({
      type: "info",
      message: "请选择至少一个信息记录",
    });
  } else {
    ElMessageBox.confirm(`是否删除${selections.value.length}企业装置大修详细信息？删除后不可恢复!`, "确认信息", {
      type: "warning",
      distinguishCancelAndClose: true,
      confirmButtonText: "删除",
      cancelButtonText: "取消",
    })
        .then(() => {
          global.$api
              .deleteSafeDeviceOverhaulByIds({
                ids: selections.value,
              }).then(({data}) => {
            queryData();
            ElMessage({
              type: "success",
              message: "您已经成功删除了信息",
            });
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "您已经取消了删除操作",
          });
        });
  }
};


/**
 * --------------定义Excel头部  要跟--------------------------
 */
let tHeader = [
  {key: "id", name: "编号"},
  {key: "name", name: "大修名称"},
  {key: "deviceType", name: "装置类型"},
  {key: "content", name: "检修内容"},
  {key: "cause", name: "检修原因"},
  {key: "deviceHeadName", name: "(设施负责人)"},
  {key: "deviceHeadPhone", name: "(设施负责人电话)"},
  {key: "startTime", name: "开始时间"},
  {key: "expectEndTime", name: "计划结束时间"},
  {key: "actualEndTime", name: "实际结束时间"},
  {key: "headName", name: "大修责任人"},
  {key: "headPhone", name: "大修责任人电话"},
  {key: "remark", name: "备注"},
  {key: "auditStatus", name: "审核状态"},
  {key: "auditDate", name: "审核时间"},
  {key: "orgId", name: "所属单位"},
  {key: "sort", name: "排序号"},
  {key: "updateUser", name: "更新人"},
  {key: "updateTime", name: "更新时间"},
  {key: "createUser", name: "创建人"},
  {key: "createTime", name: "创建时间"},
];


/**
 * --------------导出功能--------------------------
 */
const handleExport = () => {
  let data = Object.assign({}, searchForm.value.model, {});
  let obj = global.$delUndefined(data);
  global.$api.getSafeDeviceOverhaulList(obj).then(({data}) => {
    if (data.status === 'OK') {
      let exportData = data.data;
      let excelObject = {
        fileName: "企业装置大修信息表", //文件名
        tHeader: tHeader, //生成Excel表格的头部标题栏
        excelData: exportData, //需要导出Excel的数据集合
      };
      global.$exportExcel.exportExcel(excelObject);
    }
  });
};
</script>
